<!--
 * @Author: 冕上 cxm66888@163.com
 * @Date: 2025-01-01 00:00:00
 * @LastEditors: 冕上 cxm66888@163.com
 * @LastEditTime: 2025-11-21 11:50:18
 * @Description: 会员折扣策略创建/编辑
 * 
 * Copyright (c) 2025 by xiaoMing.Cao, All Rights Reserved. 
-->
<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑折扣策略' : '新增折扣策略' }}</span>
        </div>
      </template>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="discount-form" style="max-width: 800px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="策略ID" prop="strategyId">
              <el-input v-model="form.strategyId" placeholder="请输入策略ID" :disabled="isEdit" maxlength="20" show-word-limit />
              <div class="form-tip">策略ID必须唯一，创建后不可修改</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="策略类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择策略类型" style="width: 100%">
                <el-option label="开通优惠" value="open" />
                <el-option label="续费优惠" value="renew" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="折扣比例" prop="discount">
              <el-input-number v-model="form.discount" :min="0.1" :max="1" :step="0.1" :precision="1" style="width: 100%" placeholder="请输入折扣比例" />
              <div class="form-tip">折扣比例：0.5 = 5折，1.0 = 原价（范围：0.1-1.0）</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="触发条件" prop="userCondition">
              <el-select v-model="form.userCondition" placeholder="请选择触发条件" style="width: 100%" @change="handleUserConditionChange">
                <el-option label="注册天数" value="register_day" />
                <el-option label="访问过VIP页" value="visited_vip" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 注册天数输入（当选择注册天数时显示） -->
        <el-row v-if="form.userCondition === 'register_day'" :gutter="20">
          <el-col :span="12">
            <el-form-item label="注册天数" prop="registerDays">
              <el-input-number v-model="form.registerDays" :min="1" :max="365" placeholder="请输入注册天数" style="width: 100%" />
              <div class="form-tip">用户注册天数达到此值时可触发折扣（范围：1-365天）</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择开始时间" style="width: 100%" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择结束时间" style="width: 100%" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否启用" prop="isEnabled">
              <el-switch v-model="form.isEnabled" :active-value="true" :inactive-value="false" active-text="启用" inactive-text="禁用" />
              <div class="form-tip">只有启用的策略才会在前端生效</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { getMemberDiscountDetail, createMemberDiscount, updateMemberDiscount } from '@/api/memberDiscount';

  const route = useRoute();
  const router = useRouter();

  // 响应式数据
  const formRef = ref();
  const submitLoading = ref(false);
  const isEdit = computed(() => !!route.params.id);

  // 表单数据
  const form = reactive({
    strategyId: '',
    type: '',
    discount: 0.5,
    startTime: '',
    endTime: '',
    userCondition: '',
    registerDays: 1,
    isEnabled: true
  });

  // 表单验证规则
  const rules = {
    strategyId: [
      { required: true, message: '请输入策略ID', trigger: 'blur' },
      { min: 3, max: 20, message: '策略ID长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    type: [{ required: true, message: '请选择策略类型', trigger: 'change' }],
    discount: [
      { required: true, message: '请输入折扣比例', trigger: 'blur' },
      { type: 'number', min: 0.1, max: 1, message: '折扣比例必须在 0.1 到 1 之间', trigger: 'blur' }
    ],
    startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
    userCondition: [{ required: true, message: '请选择触发条件', trigger: 'change' }],
    registerDays: [
      {
        validator: (rule, value, callback) => {
          if (form.userCondition === 'register_day') {
            if (!value || value < 1 || value > 365) {
              callback(new Error('注册天数必须在 1 到 365 之间'));
            } else {
              callback();
            }
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ]
  };

  // 获取详情
  const getDetail = async id => {
    try {
      const response = await getMemberDiscountDetail(id);
      const data = response.data;

      // 将时间戳转换为日期字符串
      const formatTimestamp = timestamp => {
        if (!timestamp) return '';
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      };

      Object.assign(form, {
        strategyId: data.strategyId,
        type: data.type,
        discount: data.discount,
        startTime: formatTimestamp(data.startTime),
        endTime: formatTimestamp(data.endTime),
        userCondition: data.userCondition,
        registerDays: data.registerDays || 1,
        isEnabled: data.isEnabled
      });
    } catch (error) {
      console.error('获取详情失败:', error);
      ElMessage.error('获取详情失败');
    }
  };

  // 触发条件变化
  const handleUserConditionChange = () => {
    // 如果切换为非注册天数，清空registerDays
    if (form.userCondition !== 'register_day') {
      form.registerDays = 1;
    }
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      await formRef.value.validate();

      submitLoading.value = true;

      // 验证时间
      const startTime = new Date(form.startTime).getTime();
      const endTime = new Date(form.endTime).getTime();

      if (startTime >= endTime) {
        ElMessage.error('结束时间必须大于开始时间');
        submitLoading.value = false;
        return;
      }

      // 验证注册天数
      if (form.userCondition === 'register_day' && (!form.registerDays || form.registerDays < 1 || form.registerDays > 365)) {
        ElMessage.error('注册天数必须在 1 到 365 之间');
        submitLoading.value = false;
        return;
      }

      // 准备提交数据：将时间字符串转换为时间戳
      const submitData = {
        strategyId: form.strategyId,
        type: form.type,
        discount: form.discount,
        startTime: startTime,
        endTime: endTime,
        userCondition: form.userCondition,
        isEnabled: form.isEnabled
      };

      // 只有当userCondition为register_day时才添加registerDays
      if (form.userCondition === 'register_day') {
        submitData.registerDays = form.registerDays;
      }

      if (isEdit.value) {
        await updateMemberDiscount(route.params.id, submitData);
        ElMessage.success('更新成功');
      } else {
        await createMemberDiscount(submitData);
        ElMessage.success('创建成功');
      }

      router.push('/member-discount/list');
    } catch (error) {
      if (error !== false) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败');
      }
    } finally {
      submitLoading.value = false;
    }
  };

  // 取消
  const handleCancel = () => {
    router.push('/member-discount/list');
  };

  // 生命周期
  onMounted(() => {
    if (isEdit.value) {
      getDetail(route.params.id);
    }
  });
</script>

<style lang="scss" scoped>
  .app-container {
    padding: 20px;
  }

  .card-header {
    font-size: 18px;
    font-weight: bold;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .discount-form {
    .form-tip {
      font-size: 12px;
      color: #909399;
      margin-top: 4px;
      line-height: 1.5;
    }
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
  }

  :deep(.el-input-number) {
    width: 100%;
  }
</style>
